package com.ch4;

import java.util.ArrayList;
import java.util.Collections;

/**
 * @author woldier
 * @version 1.0
 * @description 局部变量unsafe
 * @date 2023/4/19 15:34
 **/
public class Demo3 {


    static final int THREAD_NUMBER = 2;
    static final int LOOP_NUMBER = 200;

    public static void main(String[] args) {
        ThreadSafe threadSafe = new ThreadSafe();
        for (int i = 0; i < LOOP_NUMBER; i++) {
            new Thread(() -> threadSafe.method1(LOOP_NUMBER)).start();
        }
    }

    static class ThreadSafe {
        ArrayList<String> list = new ArrayList<>();

        public void method1(int loopNumber) {
            for (int i = 0; i < loopNumber; i++) { // { 临界区, 会产生竞态条件
                method2();
                method3();// } 临界区
            }
        }

        private void method2() {
            list.add("1");
        }

        private void method3() {
            list.remove(0);
        }
    }
}

